﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Devices;
using Utils;
using Model;

namespace HowHigh
{
    public partial class GetDegree : PhoneApplicationPage
    {
        PhotoCamera cam;
        Project currentProject = App.Current.CurrentProject;
        AccelerometerHelper accHelper;

        public GetDegree()
        {
            InitializeComponent();
            this.DataContext = App.Current.AppInfo;
            Loaded += new RoutedEventHandler(GetDegree_Loaded);
        }

        void GetDegree_Loaded(object sender, RoutedEventArgs e)
        {
            accHelper = new AccelerometerHelper();
            accHelper.Start();
            // Check to see if the camera is available on the device.
            if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true))
            {
                    // Otherwise, use standard camera on back of device.
                cam = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
                previewTransform.Rotation = cam.Orientation;
                //Set the VideoBrush source to the camera.
                viewfinderBrush.SetSource(cam);
            }
            else
            {
                // The camera is not supported on the device.
                this.Dispatcher.BeginInvoke(delegate()
                {
                    // Write message.
                    textBlock1.Text = App.Current.AppInfo.NoCamero;
                });

                button1.IsEnabled = false;
            }
        }


        private void button1_Click(object sender, RoutedEventArgs e)
        {
            currentProject.Degree = accHelper.Get();
            currentProject.Update();
            Code.GpsHelper.SetLocation(Dispatcher, loc => currentProject.FirstLocation = loc);
            NavigationService.GoBack();
        }
        
        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            if (cam != null)
            {
                // Dispose camera to minimize power consumption and to expedite shutdown.
                cam.Dispose();

            }
        }
    }
}